package com.siwei.mes.service.erp.impl;

import com.siwei.mes.entity.RwdextraIronMark;
import com.siwei.mes.entity.materials.Materials;
import com.siwei.mes.entity.sync.erp.ErpProject;
import com.siwei.mes.enums.MaterialsEnum;
import com.siwei.mes.mapper.erp.RwdextraIronMarkMapper;
import com.siwei.mes.mapper.materials.MaterialsMapper;
import com.siwei.mes.mapper.syncErp.ErpProjectMapper;
import com.siwei.mes.service.erp.RwdextraIronMarkService;
import com.siwei.mes.service.materials.MaterialsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 铁标中间表-erp任务单配合比为空或者1,2,3(RwdextraIronMark)表服务实现类
 *
 * @author linzi
 * @since 2025-07-02 16:11:58
 */
@Slf4j
@Service
public class RwdextraIronMarkServiceImpl implements RwdextraIronMarkService {
    @Resource
    private RwdextraIronMarkMapper rwdextraIronMarkMapper;
    @Resource
    private ErpProjectMapper erpProjectMapper;
    @Resource
    private MaterialsService materialsService;
    @Resource
    private MaterialsMapper materialsMapper;

    @Override
    public void addInfo(Integer frwdh, String gcmc, String tpz) {
        try {
            log.info("开始判断是否需要插入铁标中间表，任务单：【{}】，工程名称：【{}】，砼品种：【{}】", frwdh, gcmc, tpz);
            ErpProject erpProject = erpProjectMapper.selectByName(gcmc);
            if (erpProject == null || erpProject.getIsIronMark() == null || erpProject.getIsIronMark() == 0) {
                log.info("工程名称：【{}】非铁标工程，直接跳过！", gcmc);
                return;
            }

            Materials materials = materialsService.checkIsExist(MaterialsEnum.CONCRETE.getCode(), MaterialsEnum.CONCRETE.getName(), tpz);

            if (materials == null) {
                log.info("物料信息不存在，直接跳过！");
                return;
            }
            if (StringUtils.isNotBlank(materials.getPhbNo())) {
                log.info("物料信息已经绑定了配合比，直接跳过！");
                return;
            }

            RwdextraIronMark ironMark = new RwdextraIronMark();
            ironMark.setFrwdh(frwdh);
            ironMark.setMaterialsId(materials.getId());

            RwdextraIronMark rwdextraIronMark = rwdextraIronMarkMapper.selectOne(ironMark);
            if (rwdextraIronMark == null) {
                rwdextraIronMarkMapper.insertSelective(ironMark);
            }

            materials.setIsIronMark(1);
            materials.setUpdateTime(new Date());
            materialsMapper.updateByPrimaryKeySelective(materials);
        } catch (Exception e) {
            log.error("添加铁标中间表失败，任务单：【{}】，工程名称：【{}】，砼品种：【{}】", frwdh, gcmc, tpz, e);
        }
    }
}
